//
//  File.swift
//
//
//  Created by didi on 2022/9/8.
//

import Vapor

struct SystemErrorMiddleware: AsyncMiddleware {
    func respond(to request: Request, chainingTo next: AsyncResponder) async throws -> Response {
        do {
            return try await next.respond(to: request)
        } catch {
            var title = "Error"
            var message = error.localizedDescription
            var status: HTTPStatus = .ok
            if let err = error as? AbortError {
                title = String(err.status.code)
                message = err.reason
                status = err.status
            }
            let template = SystemErrorPageTemplate(.init(title: title, message: message))
            return request.templates.renderHtml(template, status: status)
        }
    }
}
